package com.jiangnan.myview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.widget.LinearLayout
import com.jiangnan.R

class RoundedLinearLayout @JvmOverloads constructor(
    context: Context, 
    attrs: AttributeSet? = null, 
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    // 默认圆角半径为0，单位为像素
    private var cornerRadius: Float = 10f
    private val clipPath = Path()

    init {
        // 读取自定义属性
        attrs?.let {
            val a = context.obtainStyledAttributes(it, R.styleable.RoundedLinearLayout)
            cornerRadius = a.getDimension(R.styleable.RoundedLinearLayout_cornerRadius, 0f)
            a.recycle()
        }
        // 为确保 onDraw 被调用
        setWillNotDraw(false)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        // 重置 Path 并添加圆角矩形
        clipPath.reset()
        clipPath.addRoundRect(
            RectF(0f, 0f, w.toFloat(), h.toFloat()),
            cornerRadius,
            cornerRadius,
            Path.Direction.CW
        )
        clipPath.close()
    }

    override fun dispatchDraw(canvas: Canvas) {
        // 保存画布状态，然后剪裁后再绘制子 View
        canvas.save()
        canvas.clipPath(clipPath)
        super.dispatchDraw(canvas)
        canvas.restore()
    }
}